﻿using Tszy.Unlimited.Base.Features;
using Tszy.Unlimited.Data.UnitOfWorks.Defaults;

namespace Tszy.Unlimited.Data.Features;

/// <summary>
/// 使用 TransactionScope 做为事务。
/// </summary>
/// <typeparam name="TRequest"></typeparam>
/// <typeparam name="TResponse"></typeparam>
public abstract class DefaultTransactionFunctionFeatureHandler<TRequest, TResponse> : FunctionFeatureHandler<TRequest, TResponse>
    where TRequest : FunctionFeatureRequest<TResponse>
{
    /// <summary>
    /// 初始化。
    /// </summary>
    /// <param name="transaction">是否启用事务。</param>
    protected DefaultTransactionFunctionFeatureHandler(bool transaction = true) : base(transaction)
    {
        this.transaction = transaction;
    }

    /// <summary>
    /// 
    /// </summary>
    /// <param name="request"></param>
    /// <param name="cancellationToken"></param>
    /// <returns></returns>
    protected override async Task OnHandleAsync(TRequest request, CancellationToken cancellationToken)
    {
        if (transaction)
        {
            using var context = new DefaultUnitOfWork();

            await OnExecuteAsync(request, cancellationToken);

            context.Commit();
        }
        else
        {
            await OnExecuteAsync(request, cancellationToken);
        }
    }
}

/// <summary>
/// 使用 TransactionScope 做为事务。
/// </summary>
/// <typeparam name="TRequest"></typeparam>
/// <typeparam name="TResponse"></typeparam>
public abstract class DefaultTransactionFunctionRecordFeatureHandler<TRequest, TResponse> : FunctionRecordFeatureHandler<TRequest, TResponse>
    where TRequest : FunctionRecordFeatureRequest<TResponse>
{
    /// <summary>
    /// 初始化。
    /// </summary>
    /// <param name="transaction">是否启用事务。</param>
    protected DefaultTransactionFunctionRecordFeatureHandler(bool transaction = true) : base(transaction)
    {
        this.transaction = transaction;
    }

    /// <summary>
    /// 
    /// </summary>
    /// <param name="request"></param>
    /// <param name="cancellationToken"></param>
    /// <returns></returns>
    protected override async Task OnHandleAsync(TRequest request, CancellationToken cancellationToken)
    {
        if (transaction)
        {
            using var context = new DefaultUnitOfWork();

            await OnExecuteAsync(request, cancellationToken);

            context.Commit();
        }
        else
        {
            await OnExecuteAsync(request, cancellationToken);
        }
    }
}